package com.sunlake.spring.main.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * Spring Security配置类
 * 配置安全策略，集成JWT认证
 * @author by liuhanzhi
 */
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableMethodSecurity(securedEnabled = true)
public class SecurityConfig {
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                // 关闭CSRF保护
                .csrf(AbstractHttpConfigurer::disable)
                // 启用CORS
                .cors(Customizer.withDefaults())
                // 设置会话管理为无状态
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                // 配置请求授权
                .authorizeHttpRequests(authorize -> authorize

                        // 允许所有认证相关的请求
                        .requestMatchers("/**").permitAll()
                        // 允许公共接口请求
                        .requestMatchers("/api/public/**").permitAll()
                        // 允许所有认证相关的请求
                        .requestMatchers("/api/auth/**", "/api/public/**").permitAll()
                        // 需要ADMIN角色访问的端点
                        .requestMatchers("/api/admin/**").hasRole("ADMIN")
                        // 需要COUNSELOR或ADMIN角色访问的端点
                        .requestMatchers("/api/counselor/**").hasAnyRole("COUNSELOR", "ADMIN")
                        // 其他所有请求都需要认证
                        .anyRequest().authenticated()
                )
                // 添加JWT过滤器
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

}